package com.zhugang.week13.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: isValidBST
 * @author: chanzhugang
 * @create: 2023/01/10 00:01
 */
public class IsValidBST {

    /**
     * 98 验证二叉搜索树
     * https://leetcode.cn/problems/validate-binary-search-tree/
     *
     * @param root
     * @return
     */
    List<Integer> list = new ArrayList<>();

    public boolean isValidBST(TreeNode root) {
        /**
         * 中序遍历，如果是升序则是二叉搜索树
         */
        dfs(root);
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i) >= list.get(i + 1)) {
                return false;
            }
        }
        return true;
    }

    private boolean isValid = true;

    public boolean isValidBST2(TreeNode root) {
        /**
         * 转成求最大值，最小值,
         * 返回的值并非要求解的值； 要求解的值放在全局变量中
         */
        if (root == null) {
            return true;
        }
        dfs2(root);
        return isValid;
    }

    private int[] dfs2(TreeNode root) {
        int min = root.val;
        int max = root.val;
        if (root.left != null) {
            int[] leftMinMax = dfs2(root.left);
            // 提前退出
            if (!isValid) return null;

            if (leftMinMax[1] >= root.val) {
                isValid = false;
                return null;
            }
            min = leftMinMax[0];
        }
        if (root.right != null) {
            int[] rightMinMax = dfs2(root.right);
            // 提前退出
            if (!isValid) return null;

            if (rightMinMax[0] <= root.val) {
                isValid = false;
                return null;
            }
            max = rightMinMax[1];
        }
        return new int[]{min, max};
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        list.add(root.val);
        dfs(root.right);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}